package org.estela.util;

/**
 * Kahan's summation algorithm for double type.
 * 
 * @version $Revision: 1.1 $
 * @author <a href="mailto:antonio.kantek@gmail.com">Antonio Kantek</a>
 */
public class Kahan {

	/** Current sum */
	private double sum = 0;

	/** Correction */
	private double correction = 0;

	/** Corrected addend */
	private double correctedAddend = 0;

	/**
	 * Return the current corrected value of the running sum.
	 * 
	 * @return the running sum's value
	 */
	public double value() {
		return sum + correction;
	}

	/**
	 * Return the corrected value of the current addend.
	 * 
	 * @return the corrected addend value
	 */
	public double correctedAddend() {
		return correctedAddend;
	}

	/**
	 * Add the value of an addend to the running sum.
	 * 
	 * @param the
	 *            addend value
	 */
	public void add(double addend) {
		// Correct the addend value and add it to the running sum.
		correctedAddend = addend + correction;
		double tempSum = sum + correctedAddend;

		// Compute the next correction and set the running sum.
		// The parentheses are necessary to compute the high-order
		// bits of the addend.
		correction = correctedAddend - (tempSum - sum);
		sum = tempSum;
	}
	


	/**
	 * Clear the running sum and the correction.
	 */
	public void clear() {
		sum = 0;
		correction = 0;
	}

	/**
	 * 
	 * @param doubles
	 * @return
	 */
	public static double sum(double[] doubles) {
	    double sum = 0;
	    for (int i = 0; i < doubles.length; i++) {
	      sum += doubles[i];
	    }
	    return sum;
	}
}